package com.aaron.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

public class MySQLDbHelper {
	
	private String host      = null;
	private String className = null;
	private String user      = null;
	private String password  = null;
	private Connection conn  = null;
	private boolean connected= false;
	
	private static final Logger log = Logger.getLogger("CONSOLE");  
	
	public void connect(){
		try {
			Class.forName(className);
			conn = DriverManager.getConnection(host, user, password);
			connected = true;
			log.error("JDBC连接成功！");
		} catch (Exception e) {
			e.printStackTrace();
			log.error("JDBC建立连接失败！");
		}   
	}
	
	//查询
	public ResultSet query(String sql, Object... objs) throws SQLException{
		PreparedStatement ps = conn.prepareStatement(sql);
		for(int i=0; i<objs.length; i++ ){
			//todo 类型对照
			ps.setObject(i, objs[i]);
		}
		return ps.executeQuery();
	}
	
	
	//更新
	public int update(String sql, Object...objs) throws SQLException{
		PreparedStatement ps = conn.prepareStatement(sql);
		for(int i=0; i<objs.length; i++ ){
			//todo 类型对照
			ps.setObject(i, objs[i]);
		}
		return ps.executeUpdate();
	}
	
	
	//关闭连接
	public void close() throws SQLException{
		this.conn.close();
	}
	
	
	public boolean isConnected(){
		return this.connected;
	}
	
	public MySQLDbHelper setHost(String host) {
		this.host = host;
		return this;
	}

	public MySQLDbHelper setClassName(String className) {
		this.className = className;
		return this;
	}

	public MySQLDbHelper setUser(String user) {
		this.user = user;
		return this;
	}

	public MySQLDbHelper setPassword(String password) {
		this.password = password;
		return this;
	}
}
